package com.ideal.hadoopadmin.web.controller.report;

import com.github.pagehelper.PageInfo;
import com.ideal.hadoopadmin.entity.cluster.ClusterUser;
import com.ideal.hadoopadmin.entity.cluster.user.*;
import com.ideal.hadoopadmin.entity.cluster.user.Queue;
import com.ideal.hadoopadmin.entity.report.FairSchedulerAllocation;
import com.ideal.hadoopadmin.service.cluster.ClusterUserService;
import com.ideal.hadoopadmin.service.cluster.user.QueueService;
import com.ideal.hadoopadmin.service.report.FairSchedulerAllocationService;
import com.ideal.hadoopadmin.web.controller.UIController;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by fwj on 16/3/3.
 * 队列资源报表
 */
@Controller
@RequestMapping(QueueController.PORTAL_PREFIX)
public class QueueController extends UIController {

    public final static String PORTAL_PREFIX = "/report/queue";
    private Logger logger = LoggerFactory.getLogger(QueueController.class);

    @Resource
    private ClusterUserService clusterUserService;
//    @Resource
//    private FairSchedulerAllocationService fairSchedulerAllocationService;
    @Resource
    private QueueService queueService;

    @RequestMapping("queue_list")
    public void queueList(HttpServletRequest request, Model model) {
        try {
            Map<String, Object> searchParams = WebUtils.getParametersStartingWith(request, "Q_");
            //默认不加载数据，只有当点击搜索的时候，才加载数据
            if(null != request.getParameter("isQuery") && "query".equals(request.getParameter("isQuery").toString())){
                PageInfo fairSchedulerAllocationPage = queueService.queryQueueList(searchParams, request);
                model.addAttribute("fairSchedulerAllocationPage", fairSchedulerAllocationPage);
            }

            List<ClusterUser> clusterUserList = clusterUserService.queryClusterUser();
            Collections.sort(clusterUserList, new Comparator<ClusterUser>() {     //排序
                public int compare(ClusterUser arg0, ClusterUser arg1) {
                    return arg0.getUserName().compareTo(arg1.getUserName());
                }
            });

            model.addAttribute("clusterUserList", clusterUserList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
    }

    @RequestMapping("find_queue")
    @ResponseBody
    public List<String> findQueue(Long clusterUserId) {
        List<String> queues = new ArrayList<String>();
        try {
            List<String> queue = queueService.findQueue(clusterUserId);
            queues = new ArrayList<String>(new HashSet<String>(queue)); //去重
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        //排序
        Collections.sort(queues);
        return queues;
    }

    @RequestMapping("down_all")
    public void downAll(HttpServletResponse response,Long clusterId,String queue) {
        List<Queue> queueList = queueService.queryFairSchedulerAllocationListByDown(clusterId,queue);
        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=queue_list.xls");
            HSSFWorkbook hssfWorkbook = creatSheet(queueList);
            outputStream = response.getOutputStream();
            hssfWorkbook.write(outputStream);
            response.flushBuffer();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public HSSFWorkbook creatSheet(List<Queue> queueList) {
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();//创建excel工作薄
        HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle(); //创建表格样式
        cellStyle.setWrapText(true);                        //自动换行
        HSSFSheet hssfSheet = hssfWorkbook.createSheet();//创建excel表格
        hssfSheet.setColumnWidth(0, 8000);
        hssfSheet.setColumnWidth(1, 8000);
        hssfSheet.setColumnWidth(2, 4000);
        hssfSheet.setColumnWidth(3, 4000);
        hssfSheet.setColumnWidth(4, 2000);
        hssfSheet.setColumnWidth(5, 4000);
        HSSFRow hssfRow1 = hssfSheet.createRow(0);//创建行 标题
        HSSFRow hssfRow2 = hssfSheet.createRow(1);//创建行 th名
        HSSFCell cell1 = hssfRow2.createCell(0);
        HSSFCell cell2 = hssfRow2.createCell(1);
        HSSFCell cell3 = hssfRow2.createCell(2);
        HSSFCell cell4 = hssfRow2.createCell(3);
        HSSFCell cell5 = hssfRow2.createCell(4);
        HSSFCell cell6 = hssfRow2.createCell(5);
        cell1.setCellValue(new HSSFRichTextString("用户名称"));
        cell2.setCellValue(new HSSFRichTextString("队列名称"));
        cell3.setCellValue(new HSSFRichTextString("最小资源"));
        cell4.setCellValue(new HSSFRichTextString("最大资源"));
        cell5.setCellValue(new HSSFRichTextString("最大APP"));
        cell6.setCellValue(new HSSFRichTextString("权值"));
        HSSFCellStyle thStyle = hssfWorkbook.createCellStyle();       //创建样式
        thStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);
        thStyle.setFillForegroundColor(new HSSFColor.GREY_25_PERCENT().getIndex());
        thStyle.setFillBackgroundColor(new HSSFColor.GREY_25_PERCENT().getIndex());
        cell1.setCellStyle(thStyle);
        cell2.setCellStyle(thStyle);
        cell3.setCellStyle(thStyle);
        cell4.setCellStyle(thStyle);
        cell5.setCellStyle(thStyle);
        cell6.setCellStyle(thStyle);
        for (int i = 0; i < queueList.size(); i++) {
            HSSFRow hssfRow = hssfSheet.createRow(i + 2);//创建行
            HSSFCell hssfCell1 = hssfRow.createCell(0);
            HSSFCell hssfCell2 = hssfRow.createCell(1);
            HSSFCell hssfCell3 = hssfRow.createCell(2);
            HSSFCell hssfCell4 = hssfRow.createCell(3);
            HSSFCell hssfCell5 = hssfRow.createCell(4);
            HSSFCell hssfCell6 = hssfRow.createCell(5);
            hssfCell1.setCellStyle(cellStyle);
            hssfCell2.setCellStyle(cellStyle);
            hssfCell3.setCellStyle(cellStyle);
            hssfCell4.setCellStyle(cellStyle);
            hssfCell5.setCellStyle(cellStyle);
            hssfCell6.setCellStyle(cellStyle);
            hssfCell1.setCellValue(new HSSFRichTextString(queueList.get(i).getClusterUser().getUserName()));
            hssfCell2.setCellValue(new HSSFRichTextString(queueList.get(i).getQueueName()));
            hssfCell3.setCellValue(new HSSFRichTextString(queueList.get(i).getMinResource() + "M" + queueList.get(i).getMinCpu() + "核"));
            hssfCell4.setCellValue(new HSSFRichTextString(queueList.get(i).getMaxResource() + "M" + queueList.get(i).getMaxCpu() + "核"));
            hssfCell5.setCellValue(new HSSFRichTextString(queueList.get(i).getMaxApp() + ""));
            hssfCell6.setCellValue(new HSSFRichTextString(queueList.get(i).getWeight() + ""));
        }
        return hssfWorkbook;
    }

    @Override
    public String getPortalPrefix() {
        return PORTAL_PREFIX;
    }
}
